package com.taotao.search.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.search.bean.Item;
import com.taotao.search.bean.SearchResult;

@Service
public class SearchItemService {
	
	@Autowired
	private HttpSolrServer httpSolrServer;
	
	public SearchResult searchItems(String keyword, Integer page, Integer rows) throws Exception {
		SolrQuery query = new SolrQuery();
		query.setQuery("title:"+keyword +" AND status:1 ");
		//设置分页 start = 0 就是从0开始，rows=5当前返回5条记录，第二页就是变化start这个值为5就可以了。
		query.setStart((Math.max(page, 1)-1)*rows);
		query.setRows(rows);
		
		//是否设置高亮显示
		boolean isHighlighting = !StringUtils.equals("*", keyword) && StringUtils.isNotEmpty(keyword);;
		
		if(isHighlighting) {
			query.setHighlight(true);
			query.addHighlightField("title");
			query.setHighlightSimplePre("<em>");
			query.setHighlightSimplePost("</em>");
		}
		
		//执行查询
		QueryResponse queryResponse = this.httpSolrServer.query(query);

		List<Item> items = queryResponse.getBeans(Item.class);
		
		if(isHighlighting) {
			  // 将高亮的标题数据写回到数据对象中
            Map<String, Map<String, List<String>>> map = queryResponse.getHighlighting();
            for (Map.Entry<String, Map<String, List<String>>> highlighting : map.entrySet()) {
                for (Item item : items) {
                    if (!highlighting.getKey().equals(item.getId().toString())) {
                        continue;
                    }
                    item.setTitle(StringUtils.join(highlighting.getValue().get("title"), ""));
                    break;
                }
            }
		}
		return new SearchResult(queryResponse.getResults().getNumFound(), items);
	}

}
